package com.zxl.yjb.im.fragment;

import android.view.View;
import android.widget.AdapterView;

import com.zxl.yjb.bean.CanChatBean;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.DisplayUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.fragment.IHistoryDataResultCallback;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 作者：ssy on 2018/5/28 19:30
 * 邮箱：1161209667@qq.com
 * 简介：如果有需要过滤聊天列表，可以根据extra字段来判断，判断的条件通过隐身意图传过来；
 */
public class MyConversationListFragment extends ConversationListFragment {
    public List<Conversation> conversationList;
    @Override
    public void getConversationList(Conversation.ConversationType[] conversationTypes, final IHistoryDataResultCallback<List<Conversation>> callback) {
        RongIMClient.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {

            public void onSuccess(List<Conversation> conversations) {
                //遍历这个集合，获取每个用户的最后一条聊天消息，取出extra字段，来过滤
               /* Iterator<Conversation> iterator = conversations.iterator();
                while (iterator.hasNext()) {
                    String extra = "";
                    MessageContent latestMessage = iterator.next().getLatestMessage();
                    if (latestMessage instanceof TextMessage) {
                        extra = ((TextMessage) latestMessage).getExtra();
                    } else if (latestMessage instanceof ImageMessage) {
                        extra = ((ImageMessage) latestMessage).getExtra();
                    } else if (latestMessage instanceof LocationMessage) {
                        extra = ((LocationMessage) latestMessage).getExtra();
                    }
                    if (extra.equals("条件")) {
                        iterator.remove();
                    }
                }
                */
                conversationList = conversations;
                if (callback != null) {
                    callback.onResult(conversations);
                }
            }

            public void onError(RongIMClient.ErrorCode e) {
                if (callback != null) {
                    callback.onError();
                }
            }
        }, conversationTypes);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        super.onItemClick(parent, view, position, id);
        getCanChat(conversationList.get(position).getTargetId(),parent, view, position, id);
    }


    @Override
    public void onPortraitItemClick(View v, UIConversation data) {
//        super.onPortraitItemClick(v, data);
        getCanChatHead(v,data);
    }

    private void getCanChat(String targetId, final AdapterView<?> parent, final View view, final int position, final long id)
    {
        DataManager dataManager = new DataManager();
        Map<String,String> map = new HashMap<>();
        map.put("uid",targetId);
        ObserverOnNextListener<CanChatBean> listener = new ObserverOnNextListener<CanChatBean>() {
            @Override
            public void onNext(CanChatBean canChatBean) {

                final UIConversation uiConversation = (UIConversation)parent.getAdapter().getItem(position);
                Conversation.ConversationType conversationType = uiConversation.getConversationType();
                if ("1".equals(canChatBean.getCanchar1no2()))
                {

                    if (getGatherState(conversationType)) {
                        RongIM.getInstance().startSubConversationList(getActivity(), conversationType);
                    } else {
                        if (RongContext.getInstance().getConversationListBehaviorListener() != null && RongContext.getInstance().getConversationListBehaviorListener().onConversationClick(getActivity(), view, uiConversation)) {
                            return;
                        }

                        uiConversation.setUnReadMessageCount(0);
                        RongIM.getInstance().startConversation(getActivity(), conversationType, uiConversation.getConversationTargetId(), uiConversation.getUIConversationTitle());
                    }
                }
                else if("2".equals(canChatBean.getCanchar1no2()))
                {
                    DisplayUtil.diaplayDialogSingleButton(getActivity(), "提示", "订单或求助已失效，无法继续聊天", "确定",new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            RongIM.getInstance().removeConversation(uiConversation.getConversationType(), uiConversation.getConversationTargetId(), (RongIMClient.ResultCallback)null);
                        }
                    });
                }
            }
        };
        dataManager.canRYChat(new ProgressObserver<CanChatBean>(listener,getActivity()),map);
    }


    private void getCanChatHead(final View v,final UIConversation data)
    {
        DataManager dataManager = new DataManager();
        Map<String,String> map = new HashMap<>();
        map.put("uid",data.getConversationTargetId());
        ObserverOnNextListener<CanChatBean> listener = new ObserverOnNextListener<CanChatBean>() {
            @Override
            public void onNext(CanChatBean canChatBean) {

                if ("1".equals(canChatBean.getCanchar1no2()))
                {
                    Conversation.ConversationType conversationType = data.getConversationType();
                    if (getGatherState(conversationType)) {
                        RongIM.getInstance().startSubConversationList(getActivity(), conversationType);
                    } else {
                        if (RongContext.getInstance().getConversationListBehaviorListener() != null && RongContext.getInstance().getConversationListBehaviorListener().onConversationClick(getActivity(), v, data)) {
                            return;
                        }

                        data.setUnReadMessageCount(0);
                        RongIM.getInstance().startConversation(getActivity(), conversationType, data.getConversationTargetId(), data.getUIConversationTitle());
                    }
                }
                else if("2".equals(canChatBean.getCanchar1no2()))
                {
                    DisplayUtil.diaplayDialogSingleButton(getActivity(), "提示", "订单已结束，不能继续聊天", "确定",new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            RongIM.getInstance().removeConversation(data.getConversationType(), data.getConversationTargetId(), (RongIMClient.ResultCallback)null);
                        }
                    });
                }
            }
        };
        dataManager.canRYChat(new ProgressObserver<CanChatBean>(listener,getActivity()),map);
    }
}
